﻿using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Text;
using System.Linq;

namespace NDF.Test
{
    [TestClass]
    public class RegexTest
    {
        [TestMethod]
        public void TestMethod1()
        {
            string commandText = @"SELECT * FROM sys.tables WHERE
name LIKE N'%' + @name + N'%' AND name LIKE N'%' + @name1 + N'%'";

            //var array = Regex.Matches(commandText, "@", RegexOptions.Multiline);

            //foreach (Match item in array)
            //{
            //    Console.WriteLine(item.Value);
            //}
            var ss = GetParameters(commandText);
            foreach (var s in ss)
            {
                Console.WriteLine(s);
            }

            Console.WriteLine(ss.Length);
        }



        public string[] GetParameters(string commandText, string token = "@")
        {
            List<string> list = new List<string>();
            if (string.IsNullOrWhiteSpace(commandText))
            {
                return list.ToArray();
            }
            foreach (string line in commandText.Split('\n', '\r'))
            {
                if (string.IsNullOrWhiteSpace(line))
                {
                    continue;
                }
                for (int i = 0; i < line.Length; i++)
                {
                    var c = line[i];
                    if (c.ToString() == token)
                    {
                        StringBuilder builder = new StringBuilder();
                        while (line[++i].IsNormal())
                        {
                            builder.Append(line[i]);
                        }
                        var name = builder.ToString();
                        if (name.Length > 0) { list.Add(name); }
                    }
                }
            }
            return list.Distinct(StringComparer.CurrentCultureIgnoreCase).ToArray();
        }
    }
}
